/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  ** This notice applies to any and all portions of this file
  * that are not between comment pairs USER CODE BEGIN and
  * USER CODE END. Other portions of this file, whether 
  * inserted by the user or by software development tools
  * are owned by their respective copyright owners.
  *
  * COPYRIGHT(c) 2019 STMicroelectronics
  *
  * Redistribution and use in source and binary forms, with or without modification,
  * are permitted provided that the following conditions are met:
  *   1. Redistributions of source code must retain the above copyright notice,
  *      this list of conditions and the following disclaimer.
  *   2. Redistributions in binary form must reproduce the above copyright notice,
  *      this list of conditions and the following disclaimer in the documentation
  *      and/or other materials provided with the distribution.
  *   3. Neither the name of STMicroelectronics nor the names of its contributors
  *      may be used to endorse or promote products derived from this software
  *      without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "dma.h"
#include "spi.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "rthw.h"
#include "rtthread.h"
#include "lfs.h"
#include "spi_flash_w25qxx.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
lfs_t lfs;
lfs_file_t file1,file2;
struct lfs_config cfg;
uint8_t lfs_read_buffer[4096];
uint8_t lfs_prog_buffer[4096];
uint8_t lfs_lookahead_buffer[4096];
int lfs_read(const struct lfs_config *c, lfs_block_t block,
            lfs_off_t off, void *buffer, lfs_size_t size)
{
   W25QXX_Read_Sector((u8*)buffer,(block*c->block_size)+off,size);
   return 0;
}
int lfs_prog(const struct lfs_config *c, lfs_block_t block,
            lfs_off_t off, const void *buffer, lfs_size_t size)
{
  //W25QXX_Write((u8*)buffer,block*(c->block_size)+off,size);

	W25QXX_Write_Sector((u8*)buffer,(block*c->block_size)+off,size);
  return 0;
}
int lfs_erase(const struct lfs_config *c, lfs_block_t block)
{
  W25QXX_Erase_Sector(block*(c->block_size));
  return 0;
}
int lfs_sync(const struct lfs_config *c)
{
  return 0;
}
void my_lfs_init(void)
{
  cfg.read=lfs_read;
  cfg.prog=lfs_prog;
  cfg.erase=lfs_erase;
  cfg.sync=lfs_sync;
  cfg.read_size=512;
  //cfg.read_buffer=lfs_read_buffer;
  cfg.prog_size=512;
  //cfg.prog_buffer=lfs_prog_buffer;
  cfg.block_size=4096;
  cfg.block_count=100;
  //cfg.lookahead_buffer=lfs_lookahead_buffer;
  cfg.lookahead=512;
}
//static uint8_t WriteTest[8192];
//static uint8_t ReadTest[8192];
void test(void *arg)
{
    
    /*int i=0,c=0;
    int wsum=0,rsum=0;
		for(c=0;c<4096;c++)
		{
			wsum=0;
			rsum=0;
			for(i=0;i<4096;i++)
			{
					WriteTest[i]=i;
					wsum+=WriteTest[i];
			}
      W25QXX_Erase_Sector(c*4096);
			W25QXX_Write_Sector(WriteTest,c*4096,4096);
			W25QXX_Read(ReadTest,c*4096,4096);
			for(i=0;i<4096;i++)
			{
					rsum+=ReadTest[i];
			}
			RT_ASSERT(wsum==rsum);
		}*/
		//W25QXX_Erase_Chip();
		my_lfs_init();
    volatile int err=lfs_mount(&lfs,&cfg);
    if(err)
    {
      lfs_format(&lfs,&cfg);
      lfs_mount(&lfs,&cfg);
    }
    uint8_t x1[10],x2[10];
		int test_count=0;
    while(1)
    {
       
        err=lfs_file_open(&lfs,&file1,"/boot1.txt",LFS_O_RDWR|LFS_O_CREAT);			
				err=lfs_file_open(&lfs,&file2,"/boot2.txt",LFS_O_RDWR|LFS_O_CREAT);
			
        err=lfs_file_write(&lfs,&file1,&test_count,4);
				err=lfs_file_write(&lfs,&file2,&test_count,4);
			
			  //err=lfs_file_write(&lfs,&file1,"boot1_abcd",10);
			//err=lfs_file_write(&lfs,&file2,"boot2_abcd",10);
			
				err=lfs_file_seek(&lfs,&file1,0,0);
				err=lfs_file_seek(&lfs,&file2,0,0);
			
        err=lfs_file_read(&lfs,&file1,(void *)x1,10);
				err=lfs_file_read(&lfs,&file2,(void *)x2,10);
			
        lfs_file_close(&lfs,&file1);
				lfs_file_close(&lfs,&file2);
				test_count++;
        //rt_thread_delay(10);
    }
}

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
#define CONSOLE_DEVICE "uart1"
int  rt_application_init(void)
{
		 rt_thread_t x=rt_thread_create("tsst",test,RT_NULL,0x8000,6,10);
    rt_thread_startup(x);
	  return 0;
}
void rt_hw_board_init()
{
    rt_components_board_init();

#ifdef RT_USING_CONSOLE
    rt_console_set_device(CONSOLE_DEVICE);
#endif
}
#ifdef __CC_ARM
extern int Image$$RW_IRAM1$$ZI$$Limit;
#define STM32_SRAM_BEGIN    (&Image$$RW_IRAM1$$ZI$$Limit)
#elif __ICCARM__
#pragma section="HEAP"
#define STM32_SRAM_BEGIN    (__segment_end("HEAP"))
#else
extern int __bss_end;
#define STM32_SRAM_BEGIN    (&__bss_end)
#endif

#define STM32_SRAM_END          (0x20000000 + 64* 1024)
void rtthread_startup(void)
{
    /* init board */
    //rt_hw_board_init();

    /* show version */
    rt_show_version();

    /* init tick */
    rt_system_tick_init();

    /* init kernel object */
    rt_system_object_init();

    /* init timer system */
    rt_system_timer_init();

    static struct rt_memheap _heap;

    rt_memheap_init(&_heap,
                    "heap",
                    (void*)STM32_SRAM_BEGIN,
                    (rt_uint32_t)STM32_SRAM_END - (rt_uint32_t)STM32_SRAM_BEGIN);   
    /*static struct rt_memheap external_sram;
    rt_memheap_init(&external_sram,
                    "external_sram",
                    (void*)0X68000000,
                    0x100000);*/

    /* init scheduler system */
    rt_system_scheduler_init();

    /* init application */
    rt_application_init();

    /* init timer thread */
    rt_system_timer_thread_init();

    /* init idle thread */
    rt_thread_idle_init();

    /* start scheduler */
    rt_system_scheduler_start();

    /* never reach here */
    return ;
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_SPI2_Init();
  /* USER CODE BEGIN 2 */
    rtthread_startup();
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /**Initializes the CPU, AHB and APB busses clocks 
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /**Initializes the CPU, AHB and APB busses clocks 
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */

  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{ 
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
